<template>
  <div class="employee-orders">
    <el-card>
      <template #header>
        <div class="filter-bar">
          <el-input
            v-model="searchKeyword"
            placeholder="订单号"
            clearable
            style="width: 200px"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          
          <el-select v-model="statusFilter" placeholder="订单状态" clearable>
            <el-option label="全部" :value="null" />
            <el-option label="待支付" value="unpaid" />
            <el-option label="已支付" value="paid" />
            <el-option label="已发货" value="shipped" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
          
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
          
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon> 查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><RefreshLeft /></el-icon> 重置
          </el-button>
        </div>
      </template>
      
      <el-table v-loading="loading" :data="orderList" border stripe>
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="orderNo" label="订单号" width="180">
          <template #default="{ row }">
            <span class="order-no">{{ row.orderNo }}</span>
          </template>
        </el-table-column>
        <el-table-column label="订单状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="订单金额" width="120" sortable>
          <template #default="{ row }">
            <span class="price">¥{{ row.totalAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" width="100">
          <template #default="{ row }">
            {{ getPaymentText(row.paymentMethod) }}
          </template>
        </el-table-column>
        <el-table-column prop="username" label="客户" width="120" />
        <el-table-column prop="createTime" label="下单时间" width="180" sortable>
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" text @click="viewDetail(row)">
              <el-icon><View /></el-icon> 详情
            </el-button>
            <el-button
              v-if="row.status === 'paid'"
              type="warning"
              size="small"
              text
              @click="handleShip(row.id)"
            >
              <el-icon><Van /></el-icon> 发货
            </el-button>
            <el-button
              v-if="row.status === 'shipped'"
              type="success"
              size="small"
              text
              @click="handleCompleteOrder(row.id)"
            >
              <el-icon><Select /></el-icon> 完成
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination
        v-if="total > 0"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 20px; justify-content: center;"
        @size-change="loadOrders"
        @current-change="loadOrders"
      />
    </el-card>
    
    <!-- 订单详情对话框 -->
    <el-dialog v-model="detailVisible" title="订单详情" width="800px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单号">{{ currentOrder.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag :type="getStatusType(currentOrder.status)">
            {{ getStatusText(currentOrder.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="下单时间">{{ formatDateTime(currentOrder.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="支付方式">{{ getPaymentText(currentOrder.paymentMethod) }}</el-descriptions-item>
        <el-descriptions-item label="支付时间" v-if="currentOrder.payTime">
          {{ formatDateTime(currentOrder.payTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="发货时间" v-if="currentOrder.shipTime">
          {{ formatDateTime(currentOrder.shipTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="客户">{{ currentOrder.username || '-' }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ currentOrder.phone || '-' }}</el-descriptions-item>
        <el-descriptions-item label="收货地址" :span="2">{{ currentOrder.address || '-' }}</el-descriptions-item>
      </el-descriptions>
      
      <el-divider />
      
      <h4 style="margin-bottom: 15px;">商品明细</h4>
      <el-table :data="currentOrder.items || []" border>
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column label="商品图片" width="80">
          <template #default="{ row }">
            <img 
              :src="getImageUrl(row.productImage)" 
              style="width: 50px; height: 50px; object-fit: cover; border-radius: 4px;"
            />
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="商品名称" />
        <el-table-column prop="price" label="单价" width="100">
          <template #default="{ row }">
            <span class="price">¥{{ row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" width="80" align="center" />
        <el-table-column label="小计" width="100">
          <template #default="{ row }">
            <span class="price">¥{{ row.subtotal }}</span>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="order-total">
        <span>订单总额：</span>
        <span class="amount">¥{{ currentOrder.totalAmount }}</span>
      </div>
      
      <template #footer>
        <el-button 
          v-if="currentOrder.status === 'paid'" 
          type="warning"
          @click="handleShip(currentOrder.id)"
        >
          <el-icon><Van /></el-icon> 发货
        </el-button>
        <el-button 
          v-if="currentOrder.status === 'shipped'" 
          type="success"
          @click="handleCompleteOrder(currentOrder.id)"
        >
          <el-icon><Select /></el-icon> 完成订单
        </el-button>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { getAdminOrderList, getAdminOrderDetail, shipOrder, completeOrder } from '@/api/order'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Van, Select, View, Search, RefreshLeft } from '@element-plus/icons-vue'

const loading = ref(false)
const searchKeyword = ref('')
const statusFilter = ref(null)
const dateRange = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const orderList = ref([])

const detailVisible = ref(false)
const currentOrder = ref({ items: [] })

onMounted(() => {
  loadOrders()
})

const loadOrders = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      orderNo: searchKeyword.value || undefined,
      status: statusFilter.value || undefined,
      startDate: dateRange.value?.[0] || undefined,
      endDate: dateRange.value?.[1] || undefined
    }
    
    const res = await getAdminOrderList(params)
    if (res.code === 200 && res.data) {
      orderList.value = res.data.records || []
      total.value = res.data.total || 0
    }
  } catch (error) {
    console.error('加载订单列表失败:', error)
    ElMessage.error('加载订单列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadOrders()
}

const handleReset = () => {
  searchKeyword.value = ''
  statusFilter.value = null
  dateRange.value = []
  currentPage.value = 1
  loadOrders()
}

const getStatusType = (status) => {
  const types = {
    unpaid: 'warning',
    paid: 'success',
    shipped: 'primary',
    completed: 'info',
    cancelled: 'info',
    refunded: 'danger'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    unpaid: '待支付',
    paid: '已支付',
    shipped: '已发货',
    completed: '已完成',
    cancelled: '已取消',
    refunded: '已退款'
  }
  return texts[status] || '未知'
}

const getPaymentText = (method) => {
  const texts = {
    cash: '现金',
    alipay: '支付宝',
    wechat: '微信'
  }
  return texts[method] || '-'
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const getImageUrl = (url) => {
  if (!url) return 'https://via.placeholder.com/50'
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url
  }
  return 'http://localhost:8080' + url
}

const viewDetail = async (order) => {
  try {
    const res = await getAdminOrderDetail(order.id)
    if (res.code === 200 && res.data) {
      currentOrder.value = res.data
      detailVisible.value = true
    } else {
      ElMessage.error(res.message || '获取订单详情失败')
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
  }
}

const handleShip = async (orderId) => {
  try {
    await ElMessageBox.confirm('确定要发货吗？', '订单发货', {
      type: 'warning',
      confirmButtonText: '确认发货',
      cancelButtonText: '取消'
    })
    
    const res = await shipOrder(orderId)
    if (res.code === 200) {
      ElMessage.success('订单已发货')
      loadOrders()
      if (detailVisible.value) {
        detailVisible.value = false
      }
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('订单发货失败:', error)
      ElMessage.error(error.response?.data?.message || '订单发货失败')
    }
  }
}

const handleCompleteOrder = async (orderId) => {
  try {
    await ElMessageBox.confirm('确定要完成此订单吗？', '提示', {
      type: 'warning'
    })
    
    const res = await completeOrder(orderId)
    if (res.code === 200) {
      ElMessage.success('订单已完成')
      loadOrders()
      if (detailVisible.value) {
        detailVisible.value = false
      }
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('完成订单失败:', error)
      ElMessage.error(error.response?.data?.message || '完成订单失败')
    }
  }
}
</script>

<style lang="scss" scoped>
.employee-orders {
  .filter-bar {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    align-items: center;
  }
  
  .order-no {
    font-family: monospace;
    color: #409eff;
    font-size: 13px;
  }
  
  .price {
    color: #ff4d4f;
    font-weight: bold;
  }
  
  .order-total {
    margin-top: 20px;
    padding: 20px;
    background: #f5f7fa;
    border-radius: 8px;
    text-align: right;
    font-size: 16px;
    font-weight: bold;
    
    .amount {
      color: #ff4d4f;
      font-size: 20px;
      margin-left: 10px;
    }
  }
}
</style>

















